#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        int n = prices.size();
        vector<vector<int>> dp(n + 1, vector<int>(2 * k + 10));
        for (int i = 1; i < 2 * k + 1; i++) {
            if (i % 2) {
                dp[0][i] = -prices[0];
            }
        }

        for (int i = 1; i < n; i++) {
            for (int j = 0; j < 2 * k + 1; j++) {
                if (j == 0) {
                    dp[i][j] = 0;
                    continue;
                }
                if (j % 2) {
                    dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1] - prices[i]);
                }
                else {
                    dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1] + prices[i]);
                }
            }
        }

        int ans = 0;
        for (int i = 0; i < 2 * k + 1; i++) {
            ans = max(dp[n - 1][i], ans);
        }
        return ans;
    }
};